//
//  CJNetworkManager.swift
//  SwiftDemo
//
//  Created by Chris on 2017/6/27.
//  Copyright © 2017年 chris. All rights reserved.
//

import UIKit
import AFNetworking

enum CJHTTPMethod {
    case GET
    case POST
}

class CJNetworkManager: AFHTTPSessionManager {
    
    /// 全局网络管理对象
    static let sharedManager: CJNetworkManager = {
        let instance = CJNetworkManager()
        // 增加响应结果反序列化格式 text/plain
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
    lazy var userAccount = CJUserAccount()
    
    /// 用户是否登录
    var userLoginOn: Bool {
        return userAccount.access_token != nil
    }
    
    /// 拼接token的网络请求
    ///
    /// - Parameters:
    ///   - method: GET/POST
    ///   - URLString: 地址
    ///   - parameters: 参数
    ///   - completion: 回调 [json(Array/Dictionary), 是否请求成功]
    func tokenRequest(method: CJHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion:@escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        
        guard let token = userAccount.access_token else {
            
            // token为空, 执行登录操作
            NotificationCenter.default.post(name: NSNotification.Name(rawValue:CJUserShouldLoginInNotification), object: nil)
            print("token 为空, 请登录!")
            completion(nil, false)
            return
        }
        
        var parameters = parameters
        if parameters == nil {
            parameters = [String: Any]()
        }
        
        parameters!["access_token"] = token
        
        request(URLString: URLString, parameters: parameters, completion: completion)
    }
    
    
    /// 封装 GET/POST 网络请求
    ///
    /// - Parameters:
    ///   - method: GET / POST
    ///   - URLString: 地址
    ///   - parameters: 参数
    ///   - completion: 回调 [json(Array/Dictionary), 是否请求成功]
    func request(method: CJHTTPMethod = .GET, URLString: String, parameters: [String: Any]?, completion:@escaping (_ json: Any?, _ isSuccess: Bool) -> ()) {
        
        let success = { (task: URLSessionDataTask, json: Any?) in
            completion(json, true)
        }
        
        let failure = { (task: URLSessionDataTask?, error: Error) in
            
            if (task?.response as? HTTPURLResponse)?.statusCode == 403 {
                // token过期, 执行登录操作
                print("token 过期 , 请重新登录")
                
                NotificationCenter.default.post(name: Notification.Name(rawValue: CJUserShouldLoginInNotification), object: "bad token")
            }
            
            print("网络错误--\(error)")
            
            completion(nil, false)
        }
        
        if method == .GET {
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
}

// MARK: - OAuth 登录授权
extension CJNetworkManager {
    
    /// 加载accessToken
    ///
    /// - Parameters:
    ///   - code: 授权码
    ///   - completion: 回调[是否授权成功]
    class func loadOAuthAccessToken(code: String, completion: @escaping (Bool)-> ()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id": CJAppKey,
                         "client_secret": CJAppSecret,
                         "grant_type": "authorization_code",
                         "code": code,
                         "redirect_uri": CJAppRedirectUri]
        
        sharedManager.request(method: .POST, URLString: urlString, parameters: parameters) { (json, isSuccess) in
            
            // 获取accessToken数据并转化为CJUserAccount模型
            sharedManager.userAccount.yy_modelSet(with: (json as? [String: Any] ?? [:]))

            print(sharedManager.userAccount)
            
            loadUserInfo(completion: { (json) in
                
                sharedManager.userAccount.yy_modelSet(with: json)
                // 保存账号
                sharedManager.userAccount.saveAccount()
                // 结果回调
                completion(isSuccess)
            })
        }
    }
}

// MARK: - 用户信息
extension CJNetworkManager {
    
    /// 加载用户信息
    ///
    /// - Parameter completion: 加载完成后的回调[string:any]
    class func loadUserInfo(completion: @escaping ([String: Any]) -> ()) {
        
        guard let uid = sharedManager.userAccount.uid else {
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        let parameters = ["uid": uid]
        
        sharedManager.tokenRequest(URLString: urlString, parameters: parameters) { (json, isSuccess) in
    
            completion((json as? [String: Any]) ?? [:])
        }
    }
}
